package com.yidusoft.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yidusoft.core.Result;
import com.yidusoft.core.ResultGenerator;
import com.yidusoft.domain.SecMenuMember;
import com.yidusoft.domain.SecMenuRole;
import com.yidusoft.domain.SecRole;
import com.yidusoft.domain.SecUser;
import com.yidusoft.service.*;
import com.yidusoft.utils.PasswordHelper;
import com.yidusoft.utils.TreeNode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
* Created by CodeGenerator on 2017/07/18.
*/
@Controller
@RequestMapping("/sec/user")
public class SecUserController {
    @Resource
    private SecUserService secUserService;

    @Resource
    private SecMenuMemberService secMenuMemberService;





    @RequestMapping(value="/linkAddRole",method= RequestMethod.GET)
    public String linkAddRole(Model model,String id){
        model.addAttribute("id",id);
        return "secuser/user-role-add";
    }


    @RequestMapping(value="/login",method= RequestMethod.GET)
    public String login(){
        return "secuser/login";
    }

    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(HttpServletRequest request,String username,String  password, Model model){
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "用户名或密码不能为空！");
            return "secuser/login";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
              return "redirect:/sec/menu/getMenuForAvailable";

        }catch (LockedAccountException lae) {
            token.clear();
            request.setAttribute("msg", "用户已经被锁定不能登录，请与管理员联系！");
            return "secuser/login";
        } catch (AuthenticationException e) {
            token.clear();
            request.setAttribute("msg", "用户或密码不正确！");
            return "secuser/login";
        }
    }

    @RequestMapping(value="/test",method=RequestMethod.GET)
       public String test(){
        return "secuser/test";
    }


    @RequestMapping(value ="/linkAdd")
    public String linkAdd(Model model){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("UUID",UUID.randomUUID().toString());
        map.put("createDate",new Date());
        model.addAttribute("infos",map);
        return  "secuser/secuser-add";
    }

    @RequestMapping(value ="/linkList")
    public String linkList(){
        return  "secuser/secuser-list";
    }

    @RequestMapping(value ="/loadRole")
    public String loaduserrole(Model model,String id){
        model.addAttribute("id",id);
        return  "secuser/load-user-role";
    }

    @RequestMapping(value ="/linkUpdate")
    public String linkUpdate(Model model,String id){
        SecUser secUser = secUserService.findById(id);
        model.addAttribute("secUser",secUser);
        return  "secuser/secuser-update";
    }

    @PostMapping("/add")
    @ResponseBody
    public Result add(SecUser secUser) {
        //加密
        PasswordHelper.encryptPassword(secUser);
        secUserService.save(secUser);
        return ResultGenerator.genSuccessResult();
    }

   //把数据永久删除
    @PostMapping("/deleteTrue")
    @ResponseBody
    public Result deleteTrue(String  id) {
        secUserService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    //逻辑删除，数据还在
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(String  id) {
        SecUser secUser = secUserService.findById(id);
        secUser.setDeleted(1);
        secUserService.update(secUser);
        return ResultGenerator.genSuccessResult();
    }


    //逻辑删除，数据还在 批量删除
    @PostMapping("/deleteBacth")
    @ResponseBody
    public Result deleteBacth(String  ids) {
        String arr [] = ids.split(",");
        for(String str : arr){
            SecUser secUser = secUserService.findById(str);
            secUser.setDeleted(1);
            secUserService.update(secUser);
        }
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    @ResponseBody
    public Result update(SecUser secUser) {
        //加密
        PasswordHelper.encryptPassword(secUser);
        secUserService.update(secUser);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/userAddorg")
    @ResponseBody
    public Result userAddorg(String ids,String orgId) {

        String arr [] = ids.split(",");
        for(String s:arr){
          SecUser secUser =  secUserService.findById(s);
          if(orgId.equals("0")){
              secUser.setOrgId(null);
          }else{
              secUser.setOrgId(orgId);
          }

            secUserService.update(secUser);
        }
        return ResultGenerator.genSuccessResult();
    }


    @PostMapping("/detail")
    @ResponseBody
    public Result detail(String id) {
        SecUser secUser = secUserService.findById(id);
        return ResultGenerator.genSuccessResult(secUser);
    }

    @Resource
    private  SecMenuRoleService secMenuRoleService;
    @Resource
    private SecMenuService secMenuService;
    @PostMapping("/acthList")
    @ResponseBody
    public  List<TreeNode> acthList(String id) {

           List<TreeNode> treeNodes =secMenuService.menuTree();


            List<SecMenuMember> secMenuMembers = secMenuMemberService.findSecMenu(id);

            List<SecMenuRole> secMenuRoles = secMenuRoleService.findSecRoleMenu(id);

            for(SecMenuRole secMenuRole : secMenuRoles){
                for(TreeNode treeNode : treeNodes){

                    if(secMenuRole.getMenuId().equals(treeNode.getId())){
                        System.out.println(1233);
                        treeNode.setFlag("0");//角色权限
                    }

                }
            }
        for(SecMenuMember secMenuMember : secMenuMembers){
            for(TreeNode treeNode : treeNodes){

                if(secMenuMember.getMenuId().equals(treeNode.getId())){
                    treeNode.setFlag("1");//标识有权限
                }

            }
        }

        return treeNodes;
    }

    @PostMapping("/list1")
    @ResponseBody
    public Map<String,Object> list1() {
        List<SecUser> list = secUserService.getQueryAll(new SecUser());
        Map<String,Object> map = new HashMap<String,Object>();


        map.put("Rows",list);
        map.put("Total",list.size());
        return map;
    }

    @PostMapping("/list")
    @ResponseBody
    public Map<String,Object> list(@Valid SecUser secUser) {
        List<SecUser> secUsers = new ArrayList<SecUser>();
        if(secUser.getOrgId()!="") {

            String arr[] = secUser.getOrgId().split(",");
            for (int i = 0; i < arr.length; i++) {
                secUser.setOrgId(arr[i]);
                List<SecUser> list = secUserService.getQueryAll(secUser);
                secUsers.addAll(list);
            }
        }else{
            List<SecUser> list = secUserService.getQueryAll(secUser);
            secUsers.addAll(list);
        }
        Map<String,Object> map = new HashMap<String,Object>();


        map.put("Rows",secUsers);
        map.put("Total",secUsers.size());
        return map;
    }

    @Resource
    private SecRoleService secRoleService;

    @PostMapping("/rolelist")
    @ResponseBody
    public Map<String,Object> rolelist(String id) {
        List<SecRole> secRoles = secRoleService.getSecUserRoles(id);


        Map<String,Object> map = new HashMap<String,Object>();

        map.put("Rows",secRoles);
        map.put("Total",secRoles.size());

        return map;
    }



    @PostMapping("/listByPage")
    @ResponseBody
    public Result listByPage(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<SecUser> list = secUserService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @PostMapping("/userAddRole")
    @ResponseBody
    public Map<String,Object> userAddRole(String id) {

        String arr [] = id.split(",");
       List<SecRole> secRoles = secUserService.getUserNoRoleList(arr);

        Map<String,Object> map = new HashMap<String,Object>();

        map.put("Rows",secRoles);
        map.put("Total",secRoles.size());

        return map;
    }
}
